package org.raymond.iworks.study.basic.thread.arrayblockingqueue;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * ArrayBlockingQueue,有界阻塞队列,内部按先进先出的原则对元素进行排序
 */
@Slf4j
public class Demo1 {
    private static final Random random = new Random();
    private static final boolean flag = true;
    public static void main(String[] args) {
        test1();
    }

    public static void test1(){
        ArrayBlockingQueue queue = new ArrayBlockingQueue(1, true);
        Runnable producer = ()-> {
            for(int i=0; i<10; i++){
                try {
                    Integer j = random.nextInt(10);
                    log.info("生产: {}", j);
                    queue.put(j);
                } catch (InterruptedException e) {
                    log.error("", e);
                }
            }
        };
        Runnable consumer = ()-> {
            for(int i=0; i<10; i++){
                try {
                    Thread.sleep(1000*1);
                    log.info("消费: {}", queue.take());
                } catch (InterruptedException e) {
                    log.error("", e);
                }
            }
        };
        new Thread(producer).start();
        new Thread(consumer).start();
    }
}
